package com.module.overview.ui.widget

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.View
import androidx.core.content.ContextCompat
import com.common.base.app.extras.dp2px
import com.module.overview.R
import kotlin.math.min
import kotlin.math.cos
import kotlin.math.sin


/**
 *
 * 作者：sosou
 *
 * 版本：1.0
 *
 * 创建日期：2025/4/1
 *
 * 描述：多环进度图，支持动态数量的环
 *
 * 修订历史：
 *
 */
open class TripleRingView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {

    // 默认属性值
    var mode: RingMode = RingMode.FULL
        set(value) {
            field = value
            requestLayout()
            invalidate()
        }
    var strokeWidth: Float = dp2px(6).toFloat() // 环宽
    var spacing: Float = dp2px(4).toFloat() // 环间距
    var colors: List<Int> = listOf(Color.BLUE)
        set(value) {
            require(value.isNotEmpty()) { "至少需要提供1个颜色" }
            field = value
            invalidate()
        }
    var progressValues: List<Int> = listOf(100)
        set(value) {
            field = value
            invalidate()
        }
    private var normalizedProgress: List<Float> = progressValues.map { it / 100f }

    // Drawable资源ID列表
    private var drawableIds: List<Int>? = null
    private val paint = Paint(Paint.ANTI_ALIAS_FLAG)

    // 控制图标是否跟随进度
    var iconFollowsProgress: Boolean = true

    init {
        // 初始化默认值
        paint.strokeCap = Paint.Cap.ROUND

        // 从attrs中读取自定义属性
        if (attrs != null) {
            val typedArray = context.obtainStyledAttributes(
                attrs,
                R.styleable.CusTripleRingView,
                defStyleAttr,
                0
            )

            try {
                // 读取环宽
                strokeWidth = typedArray.getDimension(
                    R.styleable.CusTripleRingView_cus_tri_strokeWidth,
                    strokeWidth
                )

                // 读取环间距
                spacing = typedArray.getDimension(
                    R.styleable.CusTripleRingView_cus_tri_ringSpacing,
                    spacing
                )

                // 读取模式
                val modeValue = typedArray.getInt(
                    R.styleable.CusTripleRingView_cus_tri_ringMode,
                    if (mode == RingMode.FULL) 0 else 1
                )
                mode = if (modeValue == 0) RingMode.FULL else RingMode.HALF

                // 读取图标是否跟随进度
                iconFollowsProgress = typedArray.getBoolean(
                    R.styleable.CusTripleRingView_cus_tri_iconFollowsProgress,
                    iconFollowsProgress
                )

                // 读取颜色数组
                val colorsArrayResId = typedArray.getResourceId(
                    R.styleable.CusTripleRingView_cus_tri_ringColors,
                    0
                )

                if (colorsArrayResId != 0) {
                    val colorsArray = resources.obtainTypedArray(colorsArrayResId)
                    val colorsList = mutableListOf<Int>()

                    for (i in 0 until colorsArray.length()) {
                        colorsList.add(colorsArray.getColor(i, Color.BLUE))
                    }

                    colorsArray.recycle()

                    if (colorsList.isNotEmpty()) {
                        colors = colorsList
                    }
                }
            } finally {
                typedArray.recycle()
            }
        }
    }

    // 设置图标资源ID
    fun setDrawables(ids: List<Int>?) {
        this.drawableIds = ids
        invalidate()
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        val widthMode = MeasureSpec.getMode(widthMeasureSpec)
        val widthSize = MeasureSpec.getSize(widthMeasureSpec)
        val heightMode = MeasureSpec.getMode(heightMeasureSpec)
        val heightSize = MeasureSpec.getSize(heightMeasureSpec)

        val desiredWidth: Int
        val desiredHeight: Int

        if (widthMode == MeasureSpec.EXACTLY) {
            // 若宽度为确定值(match_parent或具体尺寸)，则按宽度计算
            desiredWidth = widthSize
            desiredHeight = if (mode == RingMode.FULL) {
                // 全圆环模式下，高度等于宽度
                widthSize
            } else {
                // 半圆环模式下，高度为宽度的一半
                widthSize / 2
            }
        } else if (heightMode == MeasureSpec.EXACTLY) {
            // 若高度为确定值，则按高度计算
            desiredHeight = heightSize
            desiredWidth = if (mode == RingMode.FULL) {
                // 全圆环模式下，宽度等于高度
                heightSize
            } else {
                // 半圆环模式下，宽度为高度的两倍
                heightSize * 2
            }
        } else {
            // 若宽高都未指定，则使用默认尺寸
            val defaultSize = 200
            desiredWidth = defaultSize
            desiredHeight = if (mode == RingMode.FULL) {
                defaultSize
            } else {
                defaultSize / 2
            }
        }

        // 应用测量结果
        val finalWidth = resolveSize(desiredWidth, widthMeasureSpec)
        val finalHeight = resolveSize(desiredHeight, heightMeasureSpec)

        setMeasuredDimension(finalWidth, finalHeight)
    }

    @SuppressLint("DrawAllocation")
    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)

        // 计算归一化进度值，确保数量与颜色数量一致
        normalizedProgress = List(colors.size) { i ->
            if (i < progressValues.size) {
                progressValues[i] / 100f
            } else {
                0f // 如果没有对应的进度值，则默认为0
            }
        }

        if (mode == RingMode.FULL) {
            drawFullRings(canvas)
        } else {
            drawHalfRings(canvas)
        }
    }

    private fun drawFullRings(canvas: Canvas) {
        val centerX = width / 2f
        val centerY = height / 2f
        val minDimension = min(width, height).toFloat()

        // 计算最大半径（考虑到strokeWidth）
        val maxRadius = (minDimension - strokeWidth) / 2f

        drawRings(canvas, centerX, centerY, maxRadius, -90f, 360f)
    }

    private fun drawHalfRings(canvas: Canvas) {
        val centerX = width / 2f
        // 向上调整圆心位置，留出图标显示空间
        val centerY = height.toFloat() - (strokeWidth / 2)

        // 半圆模式下，半径需要适当调整
        val maxRadius = width / 2f - strokeWidth

        drawRings(canvas, centerX, centerY, maxRadius, 180f, 180f)
    }

    private fun drawRings(canvas: Canvas, centerX: Float, centerY: Float,
                          maxRadius: Float, startAngle: Float, sweepAngle: Float) {
        // 绘制多个环
        for (i in colors.indices) {
            val radius = maxRadius - (i * (strokeWidth + spacing))

            if (radius <= 0) continue // 防止半径为负值

            // 绘制背景环（半透明）
            paint.color = adjustAlpha(colors[i], 0.1f)
            paint.style = Paint.Style.STROKE
            paint.strokeWidth = strokeWidth

            val rectF = RectF(
                centerX - radius,
                centerY - radius,
                centerX + radius,
                centerY + radius
            )

            canvas.drawArc(rectF, startAngle, sweepAngle, false, paint)

            // 绘制进度环
            paint.color = colors[i]

            val progressAngle = sweepAngle * normalizedProgress[i]

            // 对于完整圆环且进度为100%的情况，可以考虑直接绘制圆形而不是弧
            if (mode == RingMode.FULL && normalizedProgress[i] >= 0.9999f && sweepAngle >= 359f) {
                paint.style = Paint.Style.STROKE
                canvas.drawCircle(centerX, centerY, radius, paint)
            } else {
                canvas.drawArc(rectF, startAngle, progressAngle, false, paint)
            }

            // 绘制图标（如果有）
            drawableIds?.let { ids ->
                if (i < ids.size) {
                    val drawableId = ids[i]
                    if (drawableId != 0) { // 确保资源ID有效
                        val drawable = ContextCompat.getDrawable(context, drawableId)
                        drawable?.let {
                            val imageSize = strokeWidth

                            val imageX: Float
                            val imageY: Float

                            if (iconFollowsProgress) {
                                // 计算进度对应的角度（弧度）
                                val progressRad = if (mode == RingMode.FULL) {
                                    // 完整圆环，从-90度（顶部）开始
                                    ((startAngle + progressAngle) * Math.PI / 180f).toFloat()
                                } else {
                                    // 半圆环，从180度（左侧）开始
                                    ((startAngle + progressAngle) * Math.PI / 180f).toFloat()
                                }

                                // 根据角度计算图标坐标
                                imageX = centerX + radius * cos(progressRad) - (imageSize / 2)
                                imageY = centerY + radius * sin(progressRad) - (imageSize / 2)
                            } else {
                                // 固定位置逻辑
                                if (mode == RingMode.FULL) {
                                    // 全圆环模式下，图标放在顶部
                                    imageX = centerX - (imageSize / 2)
                                    imageY = centerY - radius - (imageSize / 2)
                                } else {
                                    // 半圆环模式下，图标放在左侧
                                    imageX = centerX - radius - (imageSize / 2)
                                    imageY = centerY - (imageSize / 2)
                                }
                            }

                            val imageRect = Rect(
                                imageX.toInt(),
                                imageY.toInt(),
                                (imageX + imageSize).toInt(),
                                (imageY + imageSize).toInt()
                            )

                            drawable.bounds = imageRect
                            drawable.draw(canvas)
                        }
                    }
                }
            }
        }
    }

    // 调整颜色透明度
    private fun adjustAlpha(color: Int, factor: Float): Int {
        val alpha = (Color.alpha(color) * factor).toInt()
        return Color.argb(
            alpha,
            Color.red(color),
            Color.green(color),
            Color.blue(color)
        )
    }

    /**
     * 设置三个环的进度值
     * @param progress1 第一个环的进度值（0-100）
     * @param progress2 第二个环的进度值（0-100）
     * @param progress3 第三个环的进度值（0-100）
     */
    fun setProgress(progress1: Int, progress2: Int, progress3: Int) {
        progressValues = listOf(progress1, progress2, progress3)
    }

    /**
     * 设置三个环的进度值
     * @param progressList 包含三个进度值的列表（0-100）
     */
    fun setProgress(progressList: List<Int>) {
        progressValues = progressList
    }
}

// 定义绘制模式枚举
enum class RingMode {
    FULL,   // 完整圆环
    HALF    // 半圆环
}